<template>
  <div ref="root" class="resolution-adaptation-container">
    <div class="resolution-adaptation-wrapper" :style="styleObj">
      <slot></slot>
    </div>
  </div>
</template>

<script>
const fractionDigit = 6;

export default {
  name: 'ResolutionAdaptationContainer',
  props: {
    canvasDesignWidth: {
      type: Number,
      required: true,
    },
    canvasDesignHeight: {
      type: Number,
      required: true,
    },
    elementDesignWidth: {
      type: Number,
      required: true,
    },
    elementDesignHeight: {
      type: Number,
      required: true,
    },
    priority: {
      type: String,
      default: 'height',
    },
  },
  computed: {
    styleObj() {
      return {
        width: `${this.elementDesignWidth}px`,
        height: `${this.elementDesignHeight}px`,
      };
    },
  },
  mounted() {
    this.calcAdaptation();
    window.addEventListener('resize', this.resize);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.resize);
  },
  methods: {
    calcAdaptation() {
      const el = this.$refs.root;

      let elementShouldHeight;
      let elementShouldWidth;

      let elementRealWidth;
      let elementRealHeight;
      if (this.priority === 'height') {
        elementShouldHeight = (
          (this.elementDesignHeight / this.canvasDesignHeight) *
          window.innerHeight
        ).toFixed(fractionDigit);
        elementShouldWidth = (
          (this.elementDesignWidth / this.elementDesignHeight) *
          elementShouldHeight
        ).toFixed(fractionDigit);

        elementRealWidth = elementShouldWidth;
        elementRealHeight = this.elementDesignHeight;
      } else {
        elementShouldWidth = (
          (this.elementDesignWidth / this.canvasDesignWidth) *
          window.innerWidth
        ).toFixed(fractionDigit);
        elementShouldHeight = (
          (this.elementDesignHeight / this.elementDesignWidth) *
          elementShouldWidth
        ).toFixed(fractionDigit);

        elementRealWidth = this.elementDesignWidth;
        elementRealHeight = elementShouldHeight;
      }

      const scaleX = (elementShouldWidth / this.elementDesignWidth).toFixed(
        fractionDigit
      );
      const scaleY = (elementShouldHeight / this.elementDesignHeight).toFixed(
        fractionDigit
      );

      el.style.transform = `scale(${scaleX}, ${scaleY})`;

      el.style.width = `${elementRealWidth}px`;
      el.style.height = `${elementRealHeight}px`;
    },
    resize() {
      window.requestAnimationFrame(() => {
        this.calcAdaptation();
      });
    },
  },
};
</script>

<style scoped lang="scss">
.resolution-adaptation-container {
  transform-origin: left top;
  // 覆盖层事件穿透
  pointer-events: none;
}

.resolution-adaptation-wrapper {
  // 覆盖层事件穿透
  pointer-events: none;
}

:deep(.resolution-adaptation-wrapper > *) {
  pointer-events: initial;
}
</style>
